package org.example;

import java.util.concurrent.CountDownLatch;
/**
 * 该程序证明64字节缓存行，不同线程操做的数据在不同的缓存行会比在同缓存行下的数据快
 */
public class CacheLinePadding {
    public static long COUNT =10_0000_0000L;

    private static class T {

        protected  long p1,p2,p3,p4,p5,p6,p7; // 8x7=56bytes,用来分割arr[0] arr[1]到不同缓存行
        //volatile要求保证线程更改数据可见性,就是任何一个线程更改了共享数据都要通知到其他共享该数据的其他线程更新数据
        public volatile long x = 0L; //8bytes,64bits
    }

    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(final String[] args) throws Exception{
        final CountDownLatch latch = new CountDownLatch(2);

        Thread t1 = new Thread(()->{
            for(long i = 0; i < COUNT; i++){
                arr[0].x=i;
            }
            latch.countDown();
        });

        Thread t2 = new Thread(()->{
            for(long j = 0; j< COUNT; j++){
                arr[1].x=j;
            }
            latch.countDown();
        });

        final  long start = System.nanoTime();
        t1.start();
        t2.start();
        latch.await();
        System.out.println((System.nanoTime() - start)/100_0000);
    }
}
